import { CATEGORY_TYPES, IHomeState, ILesson, ILessons, ISlider } from '@/typings/home';
import { IGlobalState } from '..';
import { Module } from 'vuex';

import * as Types from '../action-types';
import { getLesson, getSliders } from '@/api/home';

// 首页存储的数据
const state: IHomeState = {
    currentCategory: CATEGORY_TYPES.ALL,
    sliders: [],
    lessons: {
        hasMore: true,
        loading: false,
        offset: 0,
        limit: 5,
        list: []
    }
};

const home: Module<IHomeState, IGlobalState> = {
    namespaced: true,
    state,
    mutations: {
        [Types.SET_CATEGORY](state:any, payload:CATEGORY_TYPES) {
            state.currentCategory = payload;
        },
        [Types.SET_SLIDER_LIST](state, payload:ISlider[]) {
            state.sliders = payload;
        },
        [Types.SET_LOADING](state, payload) {
            state.lessons.loading = payload;
        },
        [Types.SET_LESSON_LIST] (state, payload) {
            state.lessons.list = [...state.lessons.list,...payload.list];
            state.lessons.hasMore = payload.hasMore;
            state.lessons.offset = state.lessons.offset + payload.list.length;
        }
    },
    actions: {
        async [Types.SET_SLIDER_LIST]({commit}) {
            let sliders = await getSliders<ILessons>();
            commit(Types.SET_SLIDER_LIST, sliders);
        },
        async [Types.SET_LESSON_LIST]({commit}) {
            if(state.lessons.loading || !state.lessons.hasMore) {
                return;
            }
            commit(Types.SET_LOADING, true);

            let lessons = await getLesson<ILessons>(state.currentCategory, state.lessons.offset, state.lessons.limit);

            commit(Types.SET_LESSON_LIST, lessons);

            commit(Types.SET_LOADING, false);
        }
    }
};

export default home;